<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 6/20/24
 * Time: 2:11 PM
 */

namespace App\Services;

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Str;

class UploadService
{
    protected static $dir = 'attachment/';

    protected static $allowTypes = [
        'jpg', 'jpeg', 'png', 'gif', 'docs', 'xml', 'txt', 'mp4'
    ];

    // 最大文件限制20M，20 * 1024 * 1024
    protected static $maxSize = 20971520;


    /**
     * 上传文件
     *
     * @param UploadedFile $file
     * @return array
     */
    public static function upload(UploadedFile $file)
    {
        $fileType = $file->getClientOriginalExtension();
        if (!in_array($fileType, self::$allowTypes)) {

            return ['err' => -1, 'msg' => '上传文件不合法'];
        }
        if ($file->getSize() > self::$maxSize) {

            return ['err' => -3, 'msg' => '上传文件超出最大限制20M'];
        }
        $fileName = self::getFileName() . '.' . $fileType;
        $realPath = $file->getRealPath();
        $result   = (new OssService())->uploadFile($fileName, $realPath);
        if (!$result) {

            return ['err' => -2, 'msg' => '文件：' . $file->getClientOriginalName() . '上传失败'];
        }

        return ['err' => 0, 'filepath' => $result];
    }


    /**
     * 获取文件名称
     *
     * @return string
     */
    private static function getFileName()
    {
        return md5(time() . Str::random(6));
    }
}
